package cn.mulanbay.persistent.query;

import cn.mulanbay.common.exception.ErrorCode;
import cn.mulanbay.common.exception.PersistentException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

/**
 * 通用查询的查询类构建规则类
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
public class QueryBuilder {

    /**
     * 构建查询条件
     * @param o
     * @return
     */
    public static QueryWrapper build(Object o) {
        try {
            QueryWrapper qw = new QueryWrapper();
            Field[] fs = o.getClass().getDeclaredFields();
            for (Field f : fs) {
                Query q = f.getAnnotation(Query.class);
                if (q != null) {
                    f.setAccessible(true);
                    Object v = f.get(o);
                    f.setAccessible(false);
                    if (q.supportNullValue()==false&&(v == null|| "".equals(v))) {
                        continue;
                    }
                    String columnName = q.column();
                    Operator op = q.op();
                    switch (op){
                        case EQ:
                            qw.eq(columnName,v);
                            break;
                        case NE:
                            qw.ne(columnName,v);
                            break;
                        case LIKE:
                            qw.like(columnName,v);
                            break;
                        case LIKE_LEFT:
                            qw.likeLeft(columnName,v);
                            break;
                        case LIKE_RIGHT:
                            qw.likeRight(columnName,v);
                            break;
                        case GT:
                            qw.gt(columnName,v);
                            break;
                        case LT:
                            qw.lt(columnName,v);
                            break;
                        case GE:
                            qw.ge(columnName,v);
                            break;
                        case LE:
                            qw.le(columnName,v);
                            break;
                        case IN:
                            qw.in(columnName,v);
                            break;
                        case NOT_IN:
                            qw.notIn(columnName,v);
                            break;
                        default:
                            break;
                    }
                }
            }
            return qw;
        } catch (Exception e) {
            throw new PersistentException(
                    ErrorCode.QUERY_BUILD_ERROR, "构建查询类PageRequest异常",e);
        }
    }
}
